<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="计划编码">
          <el-input
            v-model="searchParam.planCode"
            placeholder="请输入计划编码"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="模具管理部门">
          <SelectOriganizationDangerGrant
            @change="(ids:string) => getSelectIds(ids, '管理部门')"
            :isCheckStrictly="true"
            :isMultiple="false"
            :disabled="false"
            :data="dataObject('管理部门')"
            :selectData="searchParam.deviceDepartment"
          />
        </el-form-item>
        <el-form-item label="维修执行部门">
          <SelectOriganizationDangerGrant
            @change="(ids:string) => getSelectIds(ids, '维修执行部门')"
            :isCheckStrictly="true"
            :isMultiple="false"
            :disabled="false"
            :data="dataObject('维修执行部门')"
            :selectData="searchParam.repairDepartment"
          />
        </el-form-item>
        <el-form-item label="维修类型">
          <el-select
            v-model="searchParam.repairType"
            placeholder="请选择维修类型"
            clearable
            filterable
          >
            <el-option
              v-for="item in useDictionary('EamRepairType')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()">
          <i-ep-plus />
          新增
        </el-button>
        <!-- <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
        >
          <i-ep-delete />
          删除
        </el-button> -->
        <!-- <el-button
          @click="
            useDownload(
              '/mes/mesproducereport/reportExport',
              '计划维修',
              searchParam
            )
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        > -->
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->

        <el-table-column
          label="计划编码"
          prop="planCode"
          min-width="200"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="维修类型"
          prop="repairType"
          min-width="120"
          align="center"
          sortable
        >
          <template #default="scope">
            {{ useDictionary("EamRepairType", scope.row.repairType) }}
          </template>
        </el-table-column>
        <el-table-column
          label="计划开始日期"
          prop="planStartTime"
          min-width="150"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            {{
              scope.row.planStartTime
                ? dayjs(scope.row.planStartTime).format("YYYY-MM-DD")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="计划结束日期"
          prop="planEndTime"
          min-width="150"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            {{
              scope.row.planEndTime
                ? dayjs(scope.row.planEndTime).format("YYYY-MM-DD")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="计划状态"
          prop="planStatus"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            {{ useDictionary("RepairPlanStatus", scope.row.planStatus) }}
          </template>
        </el-table-column>
        <el-table-column
          label="模具管理部门"
          prop="deviceDepartmentName"
          min-width="140"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="维修执行部门"
          prop="repairDepartmentName"
          min-width="140"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="维修负责人"
          prop="repariDirectorName"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable
        />
        <el-table-column
          label="启用状态"
          prop="enabled"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          prop="remarks"
          min-width="300"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="300" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
            >
              <i-ep-search />
              查看
            </el-button>
            <el-button
              :disabled="scope.row.planStatus !== 0"
              type="primary"
              size="small"
              link
              @click="generateOrder(scope.row)"
            >
              <i-ep-documentChecked />

              生成工单
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
            >
              <i-ep-edit />
              编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <eamMoldrepairplan-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :assetKind="assetKind"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : getTableList())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useRouter, useRoute } from "vue-router";
import { filterOrder } from "@/utils/commonHooks";
import dayjs from "dayjs";
const router = useRouter();
const route = useRoute();

defineOptions({
  name: "EAMMOLDEAMMOLDREPAIRPLAN",
  inheritAttrs: false,
});
const props = defineProps({
  assetKind: {
    type: Number,
    default: 3,
  },
});

const { assetKind } = toRefs(props);
// 请求参数
const requestApi = "/eam/mouldrepairplan/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  planCode: "",
  planName: "",
  repairType: "",
  deviceDepartment: "",
  repairDepartment: "",
  enabled: "",
  deleted: "",
  assetKind: assetKind.value,
};

const deleteParam = {
  api: "/eam/mouldrepairplan/delete",
  data: { assetKind: assetKind.value },
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/mouldrepairplan/get/${id}`,
    method: "get",
    data: { assetKind: assetKind.value },
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开计划维修表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改计划维修";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增计划维修";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
  // if (roleObj) {
  //   router.push({
  //     path: "/eam/commonPage/commonRepairPlanDetail",
  //     query: { id: roleObj.id, assetKind: assetKind.value },
  //   });
  // } else {
  //   router.push({
  //     path: "/eam/commonPage/commonRepairPlanDetail",
  //     query: { assetKind: assetKind.value },
  //   });
  // }
}
const openDevDialog = (row) => {
  router.push({
    path: "/eam/mold/eamMoldRepairPlanDetail",
    query: { id: row.id, assetKind: assetKind.value },
  });
};
/** 打开计划维修表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "计划维修详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/eam/mouldrepairplan/deleteItem/${id}`,
      method: "post",
      data: {
        assetKind: assetKind.value,
      },
    }).then((res) => {
      ElMessage.success("删除成功！");
      search();
    });
  });
}

/** 选择组织机构并赋值id  start **/
function getSelectIds(ids: [] | string, item: string) {
  if (ids) {
    if (item == "维修执行部门") {
      searchParam.value.repairDepartment = ids;
    } else if (item == "管理部门") {
      searchParam.value.deviceDepartment = ids;
    }
  } else {
    if (item == "维修执行部门") {
      searchParam.value.repairDepartment = "";
    } else if (item == "管理部门") {
      searchParam.value.deviceDepartment = "";
    }
  }
}
const dataObject = (item: string) => {
  return {
    name: item == "维修执行部门" ? "维修执行部门" : "管理部门",

    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};
// 生成工单
const generateOrder = async ({ id }) => {
  ElMessageBox.confirm("确定生成工单吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: "/eam/mouldrepairplan/generateOrder",
      method: "post",
      data: { id },
    }).then(() => {
      ElMessage.success("生成任务成功！");
      search();
    });
  });
};
</script>
